package org.NooLab.itexx.storage.docserver.storage.db.iciql;

import java.lang.reflect.Field;
import java.lang.reflect.Method;


import org.NooLab.itexx.storage.DbFieldRequest;

public abstract class AliasAbstract implements AliasIntf {

	String name = "";
	
	public AliasAbstract(){
		
		name = this.getClass().getName().toLowerCase();
		int p= name.lastIndexOf(".");
		if (p>0){
			name = name.substring(p+1,name.length()) ;
		}
	}

	// ====================================================
	public AliasIntf getSelf(){
		return this;
	}
	
	public String getName(){
		return name;
	}

	public void setValue( String fieldname, Object fieldvalue) {
		
	}

	public Field getFieldByName(String fieldname) {
		Field field=null;
		
		Class<? extends AliasAbstract> sclass = this.getClass() ;
		
		Field[] ff = sclass.getDeclaredFields() ;
		
		try{

			for (int i=0;i<ff.length;i++){

				
				
				String _fname = ff[i].getName() ;
				
				if (_fname.toLowerCase().endsWith( fieldname.toLowerCase())){
					field = ff[i] ;
					break;
				}
			}// i->

		}catch(Exception e){
			e.printStackTrace();
		}
		
		return field;
	}

	public boolean setValue(DbFieldRequest request) {
		boolean rB=false;
		Class<?> sclass, loadedclass ;
		ClassLoader classLoader; 
		Method[] mm;
		Method m;

		sclass = this.getClass() ;
		classLoader = sclass.getClassLoader();
		mm = sclass.getMethods();
		Field[] ff = sclass.getDeclaredFields() ;
		
		try{

			for (int i=0;i<ff.length;i++){
				
				// To find a method we need the array of matching Class types.
				// Class[] argTypes = { String.class };

				// Now find a Method object for the given method.
				// Method worker = clX.getMethod("work", argTypes);
				/*
				// To INVOKE the method, we need its actual arguments, as an array.
				Object[] mData = { request.getFieldname(), request.getFieldValue() };

				// The obvious last step: invoke the method.
				mm[i].invoke( this, mData);
				 */
				String rqField = request.getFieldname();
				//if (rqField)
				
				String _fname = ff[i].getName() ;
				
				if (_fname.toLowerCase().endsWith(rqField.toLowerCase())){
					ff[i].set( this, request.getFieldValue()); 
					rB=true;
					break;
				}
			}// i->

		}catch(Exception e){
			e.printStackTrace();
		}
		ff = null;
		return rB;
	}

}
